package com.example.asus.coolweather;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.asus.coolweather.gson.Forecast;
import com.example.asus.coolweather.gson.Weather;
import com.example.asus.coolweather.service.AutoUpdateService;
import com.example.asus.coolweather.util.HttpUtil;
import com.example.asus.coolweather.util.Utility;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
   private ScrollView mWeatherLayout;
    private TextView mTitleCity;
    private TextView mTitleUpdateTime;
    private TextView mDegressText;
    private TextView mWeather;
    private LinearLayout mForecastLayout;
    private TextView mAqiText;
    private TextView mPm25Text;
    private TextView mComfortText;
    private TextView mCarWashText;
    private TextView mSportText;
    private ImageView mBing;
    public SwipeRefreshLayout swipeRefreshLayout;
    private String mWeatherId;
    public DrawerLayout drawerLayout;
    private Button mNav;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT>=21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_weather);

        mWeatherLayout = (ScrollView)findViewById(R.id.weather_layout);
        mTitleCity = (TextView)findViewById(R.id.tv_title_city);
        mTitleUpdateTime = (TextView)findViewById(R.id.tv_title_updateTime);
        mDegressText = (TextView)findViewById(R.id.tv_degree_text);
        mWeather = (TextView)findViewById(R.id.tv_weather_info);
        mForecastLayout = (LinearLayout)findViewById(R.id.forecast_layout);
        mAqiText = (TextView)findViewById(R.id.tv_api);
        mPm25Text = (TextView)findViewById(R.id.tv_pm25);
        mComfortText = (TextView)findViewById(R.id.tv_comfort);
        mCarWashText = (TextView)findViewById(R.id.tv_car_wash);
        mSportText = (TextView)findViewById(R.id.tv_sport);
        mBing = (ImageView)findViewById(R.id.iv_bing);
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        mNav = (Button)findViewById(R.id.btn_nav);

        mNav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });




        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = preferences.getString("weather",null);
        String bingPic = preferences.getString("bing_pic",null);
        if (bingPic != null){
            Glide.with(this).load(bingPic).into(mBing);
        }else {
            loadBingPic();
        }
        if (weatherString!=null){
            Weather weather = Utility.handleWeatherResponse(weatherString);
            mWeatherId  = weather.basic.weatherId;
            showWeatherInfo(weather);
        }else {

            mWeatherLayout.setVisibility(View.INVISIBLE);
            mWeatherId = getIntent().getStringExtra("weather_id");
            requestWeather(mWeatherId);
        }
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(mWeatherId);
            }
        });





    }


    /**
     * 根据天气的id请求城市的天气
     */
    public void  requestWeather(final String weatherId){

          String weatherUrl = "http://guolin.tech/api/weather?cityid="+weatherId+"&key=c7550ef6e7814802ae8c3fec62ee847c";
        HttpUtil.sendOkhttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT).show();
                        Log.d("weather","failure");
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final  Weather weather = Utility.handleWeatherResponse(responseText);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather!=null&&"ok".equals(weather.status)){
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather",responseText);
                            editor.apply();
                            showWeatherInfo(weather);
                        }else {
                            Toast.makeText(WeatherActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT).show();
                        }swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }


        });

        loadBingPic();
    }
    private void loadBingPic(){
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkhttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                   final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic",bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(mBing);
                    }
                });
            }
        });
    }

    private void showWeatherInfo(Weather weather){
        String cityname = weather.basic.cityName;
        String update = weather.basic.update.updateTime.split(" ")[1];
        String degree = weather.now.temperature+"C";
        String weatherInfo = weather.now.more.info;
        mTitleCity.setText(cityname);
        mTitleUpdateTime.setText(update);
        mDegressText.setText(degree);
        mWeather.setText(weatherInfo);
        mForecastLayout.removeAllViews();

        if (weather != null && "ok".equals(weather.status)){
            Intent intent = new Intent(this, AutoUpdateService.class);
            startService(intent);
        }else {
            Toast.makeText(WeatherActivity.this,"获取信息失败",Toast.LENGTH_SHORT).show();
        }

        for (Forecast forecast : weather.forecastsList){
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,mForecastLayout,false);
            TextView dateText = view.findViewById(R.id.tv_date);
            TextView infoText = view.findViewById(R.id.tv_info);
            TextView maxText = view.findViewById(R.id.tv_max);
            TextView minText = view.findViewById(R.id.tv_min);
            dateText.setText(forecast.date);
            infoText.setText(forecast.more.info);
            maxText.setText(forecast.temperature.max);
            minText.setText(forecast.temperature.min);
            mForecastLayout.addView(view);
        }

        if (weather.aqi != null){
            mAqiText.setText(weather.aqi.city.aqi);
            mPm25Text.setText(weather.aqi.city.pm25);

        }

        String comfort = "舒适度"+ weather.suggestion.comfort.info;
        String carWash = "洗车指数" + weather.suggestion.comfort.info;
        String sport = "运动建议"+weather.suggestion.sport.info;
        mComfortText.setText(comfort);
        mCarWashText.setText(carWash);
        mSportText.setText(sport);
        mWeatherLayout.setVisibility(View.VISIBLE);
    }


}
